<?php
/**
 * 地区设置
 * @author 江羿平<hugcolin@163.com>
 */

use Core\AdminController;
use Models\Region;
class RegionController extends AdminController {

	

	/**
	 * 列表页
	 */
	public function index(){
		$region= new Region;
		$parent_id = $this->input->get('id');
		if(!$parent_id) $parent_id = 1;
		$region = $region->find($parent_id);
		$regions = (new Region)->where('parent_id',$parent_id)->get();
		if(IS_AJAX){
			return $this->response(['region'=>$region->to_array(),'regions'=>$regions]);
		}
		$this->load->view('admin/region/index',['regions'=>$regions]);
	}

	/**
	 * 删除
	 */
	public function delete(){
		$region = (new Region)->find($this->input->post('id'));
		if($region['type'] == 1){
			$childs = (new Region)->where('parent_id',$region['id'])->get();
			$childs = arr_key($childs);
			$child_ids = array_keys($childs);
			$child_ids[] = $region['id'];
			(new Region)->where_in('parent_id',$child_ids)->deleteAll();
		}
		if($region['type'] == 2){
			(new Region)->where('parent_id',$region['id'])->deleteAll();
		}

		$region->delete($region['id']);
		echo json_encode(array('code'=>0,'msg'=>'ok'));
	}


	/**
	 * 提交保存
	 */
	public function save(){
		
		
		$data['name'] = $this->input->post('name');
		$data['en_name'] = $this->input->post('en_name');
		

		if( !$data['name'] || !$data['en_name']){
			echo json_encode(array('code'=>2,'msg'=>json_encode($data)));
			exit;
		}

		$region = new Region;
		if(intval($this->input->post('id'))){
			$region->update(intval($this->input->post('id')),$data);
			echo json_encode(array('code'=>0,'msg'=>'ok'));
		}else{
			$data['type'] = $this->input->post('type');
			$data['parent_id'] = $this->input->post('parent_id');
			$region_id = $region->add($data);
			if($region_id){
				$data['id'] = $region_id;
				echo json_encode(array('code'=>0,'msg'=>'ok','data'=>$data));	
			}else{
				echo json_encode(array('code'=>1));
			}
		}
	}

}
